package main

import (
	"encoding/json"
	"fmt"
	"os"
	"trader/cmd/server/app"
	"trader/config"
	"trader/store"

	"github.com/gin-gonic/gin"
)

func main() {
	// 读取配置
	f, ok := os.LookupEnv("TRADER_CONFIG")
	if !ok {
		f = "config.yaml"
	}
	configInst := config.NewConfig(f)
	jsonBytes, err := json.MarshalIndent(configInst, "", "  ")
	fmt.Println("config:", string(jsonBytes))

	// 配置日志
	store.SetLogger(configInst.Log)

	// 连接数据库
	engine := store.ConnectMysql(configInst.Mysql)

	// 配置应用
	gin.SetMode(configInst.Server.Mode)
	server := gin.New()
	server.Use(gin.Recovery())
	if gin.Mode() != gin.DebugMode {
		// 设置代理IP，用于获取真实IP
		err = server.SetTrustedProxies([]string{"127.0.0.1"})
		if err != nil {
			panic(fmt.Errorf("set proxy err: %v", err))
		}
	}

	app.MountRouter(server, engine, configInst)

	err = server.Run(fmt.Sprintf("0.0.0.0:%v", configInst.Server.Port))
	if err != nil {
		panic(err)
	}
}
